package service

import (
	"context"
	"errors"
	"saleforce/sf-backend-gateway/i18n"
	"saleforce/sf-backend-user/bootstrap"
	"saleforce/sf-backend-user/model"
	cst "saleforce/sf-common/constant"
	bs "saleforce/sf-common/protoc/backend-user"
	util "saleforce/sf-common/utils"
)

type MenuService struct {
	bs.UnimplementedMenuServiceServer
}

func (m MenuService) GetMenu(c context.Context, p *bs.IntIdParam) (*bs.Menu, error) {
	bootstrap.InitAll()
	value := c.Value(cst.Current_Login_User)
	lang := ""
	if m2, ok := value.(map[string]any); ok {
		if lang, ok = m2["lang"].(string); !ok {
			lang = "cn"
		}
	}
	id := p.GetId()
	if id == 0 {
		return nil, nil
	}
	byId, err := model.MenuModel{}.GetMenuById(id)
	if err != nil {
		return nil, errors.New(i18n.T(err.Error(), lang))
	}
	return &bs.Menu{
		Id:         byId.Id,
		Name:       byId.Name,
		ApiUrl:     byId.ApiUrl,
		Icon:       byId.Icon,
		MenuType:   byId.MenuType,
		ModuleLink: byId.ModuleLink,
		ParentId:   byId.ParentId,
		Status:     byId.Status,
		IsShow:     byId.IsShow,
		Created:    util.ConvertTimeToTimestamp(byId.Created),
		Updated:    util.ConvertTimeToTimestamp(byId.Updated),
	}, nil
}

func (m MenuService) GetMenuList(c context.Context, p *bs.MenuListParam) (*bs.MenuListResp, error) {
	bootstrap.InitAll()
	value := c.Value(cst.Current_Login_User)
	lang := ""
	if m2, ok := value.(map[string]any); ok {
		if lang, ok = m2["lang"].(string); !ok {
			lang = "cn"
		}
	}
	menuType := util.UnwrapInt32(p.GetMenuType())
	page := util.UnwrapInt64(p.GetPage())
	if page == nil || *page < 1 {
		*page = 1
	}
	size := util.UnwrapInt64(p.GetSize())
	if size == nil || *size < 1 {
		*size = 10
	}
	keyword := util.UnwrapString(p.GetKeyword())
	lst, err := model.MenuModel{}.ListByConditions(int(*page), int(*size), menuType, util.UnwrapInt32(p.GetStatus()), keyword)
	if err != nil {
		return nil, errors.New(i18n.T(err.Error(), lang))
	}
	count := model.MenuModel{}.CountByConditions(menuType, util.UnwrapInt32(p.GetStatus()), keyword)
	lstMenu := make([]*bs.Menu, len(lst))
	for i, menu := range lst {
		lstMenu[i] = &bs.Menu{
			Id:         menu.Id,
			Name:       menu.Name,
			ApiUrl:     menu.ApiUrl,
			Icon:       menu.Icon,
			MenuType:   menu.MenuType,
			ModuleLink: menu.ModuleLink,
			ParentId:   menu.ParentId,
			Status:     menu.Status,
			IsShow:     menu.IsShow,
			Created:    util.ConvertTimeToTimestamp(menu.Created),
			Updated:    util.ConvertTimeToTimestamp(menu.Updated),
		}
	}
	listResp := bs.MenuListResp{
		Menus: lstMenu,
		Page:  *page,
		Size:  *size,
		Total: count,
	}
	return &listResp, nil
}
